package com.jlkf.controller;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author he.hb
 * API 统一异常处理
 * 保证返回的数据始终是 json 数据，避免错误堆栈信息返回
 */
@Component
public class ApiHandleException implements HandlerExceptionResolver {

    protected static Logger logger = LoggerFactory.getLogger(ApiHandleException.class);

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.error("异常拦截：",e);

        ModelAndView mv = new ModelAndView();
        //异步判断
        if(request.getHeader("accept").contains("application/json")
                || (request.getHeader("X-Requested-With")!= null
                    && request.getHeader("X-Requested-With").contains("XMLHttpRequest"))){
            //如果抛出的是系统自定义的异常则直接转换
//            if(e instanceof CommonException) {
//                CommonException ce = (CommonException) e;
//                FastJsonJsonView view = new FastJsonJsonView();
//                Map<String, Object> attributes = new HashMap<String, Object>();
//                attributes.put("code", ce.getCode());
//                attributes.put("msg", ce.getMessage());
//                view.setAttributesMap(attributes);
//                mv.setView(view);
//            } else {
                FastJsonJsonView view = new FastJsonJsonView();
                Map<String, Object> attributes = new HashMap<String, Object>();
                attributes.put("code", -1);
                attributes.put("msg", "未知错误");
                view.setAttributesMap(attributes);
                mv.setView(view);
//            }
        }else{
            mv.setViewName("error");
        }
        return mv;
    }

}
